package org.example.service;

import org.example.entity.Ticket;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TicketService {
    private static List<Ticket> soldTickets = new ArrayList<>();

    /**
     * 保存票到销售集合中并序列化
     * @param ticket 要保存的票
     */
    public static void saveTicket(Ticket ticket) {
        //如果sold_tickets.ser不存在
        if (!new File("sold_tickets.ser").exists()) {
            soldTickets.add(ticket);
            serializeTickets();
            return;
        }

        // 保存到销售的票的集合中
        soldTickets = getSoldTickets();
        soldTickets.add(ticket);

        // 实现序列化
        serializeTickets();
    }

    /**
     * 序列化所有已售电影票
     */
    private static void serializeTickets() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("sold_tickets.ser"))) {
            oos.writeObject(soldTickets);
            System.out.println("电影票销售记录已序列化保存到 sold_tickets.ser 文件中");
        } catch (IOException e) {
            System.err.println("序列化电影票时出错: " + e.getMessage());
        }
    }

    /**
     * 反序列化已售电影票
     */
    public static List<Ticket> getSoldTickets() {
        List<Ticket> soldTickets;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("sold_tickets.ser"))) {
            soldTickets = (List<Ticket>) ois.readObject();
            System.out.println("已售电影票已从 sold_tickets.ser 文件中反序列化");
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return soldTickets;
    }
    public static void printTickets() {
        for (Ticket ticket : getSoldTickets()) {
            ticket.showTicket();
        }
    }
}
